# @Version        : 1.0
# @Update Time    : 2025/8/16 20:52
# @File           : render_template.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息
from fastapi import Request
from fastapi.templating import Jinja2Templates
from jinja2 import pass_context

from applications import settings

# 创建一个templates（模板）对象，以后可以重用。
templates = Jinja2Templates(directory="templates")


@pass_context
def authorize(ctx, power: str) -> bool:
    request: Request = ctx["request"]
    user = getattr(request.state, "user", None)
    if not user:
        return False

    username = user.username
    if username != settings.SUPERADMIN:
        permissions = request.session.get("permissions") or []
        return power in permissions
    return True


# 注册到 Jinja2 环境
templates.env.globals["authorize"] = authorize
